﻿using System;
using System.Collections.Generic;
using System.Text;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// </summary>
    public class NativeNumber : IdScriptableObject
    {

        private static Object NUMBER_TAG = "Number";

        private static int MAX_PRECISION = 100;

        public static void init(Scriptable scope, bool sealed1)
        {
            NativeNumber obj = new NativeNumber(0.0);
            obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed1);
        }

        private NativeNumber(double number)
        {
            doubleValue = number;
        }


        public override String getClassName()
        {
            return "Number";
        }


        public override void fillConstructorProperties(IdFunctionObject ctor)
        {
            int attr = ScriptableObject.DONTENUM |
                             ScriptableObject.PERMANENT |
                             ScriptableObject.READONLY;

            ctor.defineProperty("NaN", Double.NaN, attr);
            ctor.defineProperty("POSITIVE_INFINITY",
                                ScriptRuntime.wrapNumber(Double.PositiveInfinity),
                                attr);
            ctor.defineProperty("NEGATIVE_INFINITY",
                                ScriptRuntime.wrapNumber(Double.NegativeInfinity),
                                attr);
            ctor.defineProperty("MAX_VALUE",
                                ScriptRuntime.wrapNumber(Double.MaxValue),
                                attr);
            ctor.defineProperty("MIN_VALUE",
                                ScriptRuntime.wrapNumber(Double.MinValue),
                                attr);

            base.fillConstructorProperties(ctor);
        }


        public override void initPrototypeId(int id)
        {
            String s;
            int arity;
            switch (id)
            {
                case Id_constructor: arity = 1; s = "constructor"; break;
                case Id_toString: arity = 1; s = "toString"; break;
                case Id_toLocaleString: arity = 1; s = "toLocaleString"; break;
                case Id_toSource: arity = 0; s = "toSource"; break;
                case Id_valueOf: arity = 0; s = "valueOf"; break;
                case Id_toFixed: arity = 1; s = "toFixed"; break;
                case Id_toExponential: arity = 1; s = "toExponential"; break;
                case Id_toPrecision: arity = 1; s = "toPrecision"; break;
                default: throw new ArgumentException(id.ToString());
            }
            initPrototypeMethod(NUMBER_TAG, id, s, arity);
        }


        public override Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                                 Scriptable thisObj, Object[] args)
        {
            if (!f.hasTag(NUMBER_TAG))
            {
                return base.execIdCall(f, cx, scope, thisObj, args);
            }
            int id = f.methodId();
            if (id == Id_constructor)
            {
                double val = (args.Length >= 1)
                    ? ScriptRuntime.toNumber(args[0]) : 0.0;
                if (thisObj == null)
                {
                    // new Number(val) creates a new Number object.
                    return new NativeNumber(val);
                }
                // Number(val) converts val to a number value.
                return ScriptRuntime.wrapNumber(val);
            }

            // The rest of Number.prototype methods require thisObj to be Number

            if (!(thisObj is NativeNumber))
                throw incompatibleCallError(f);
            double value = ((NativeNumber)thisObj).doubleValue;

            switch (id)
            {

                case Id_toString:
                case Id_toLocaleString:
                    {
                        // toLocaleString is just an alias for toString for now
                        int base1 = (args.Length == 0)
                            ? 10 : ScriptRuntime.toInt32(args[0]);
                        return ScriptRuntime.numberToString(value, base1);
                    }

                case Id_toSource:
                    return "(new Number(" + ScriptRuntime.toString(value) + "))";

                case Id_valueOf:
                    return ScriptRuntime.wrapNumber(value);

                case Id_toFixed:
                    return num_to(value, args, DToA.DTOSTR_FIXED,
                                  DToA.DTOSTR_FIXED, -20, 0);

                case Id_toExponential:
                    return num_to(value, args, DToA.DTOSTR_STANDARD_EXPONENTIAL,
                                  DToA.DTOSTR_EXPONENTIAL, 0, 1);

                case Id_toPrecision:
                    return num_to(value, args, DToA.DTOSTR_STANDARD,
                                  DToA.DTOSTR_PRECISION, 1, 0);

                default: throw new ArgumentException(id.ToString());
            }
        }


        public override String ToString()
        {
            return ScriptRuntime.numberToString(doubleValue, 10);
        }

        private static String num_to(double val,
                                     Object[] args,
                                     int zeroArgMode, int oneArgMode,
                                     int precisionMin, int precisionOffset)
        {
            int precision;
            if (args.Length == 0)
            {
                precision = 0;
                oneArgMode = zeroArgMode;
            }
            else
            {
                /* We allow a larger range of precision than
                   ECMA requires; this is permitted by ECMA. */
                precision = ScriptRuntime.toInt32(args[0]);
                if (precision < precisionMin || precision > MAX_PRECISION)
                {
                    String msg = ScriptRuntime.getMessage1(
                        "msg.bad.precision", ScriptRuntime.toString(args[0]));
                    throw ScriptRuntime.constructError("RangeError", msg);
                }
            }
            StringBuilder sb = new StringBuilder();
            DToA.JS_dtostr(sb, oneArgMode, precision + precisionOffset, val);
            return sb.ToString();
        }

        // #string_id_map#


        public override int findPrototypeId(String s)
    {
        int id;
// #generated# Last update: 2007-05-09 08:15:50 EDT
       id = 0; String X = null; int c;
             switch (s.Length) {
            case 7: c=s.ToCharArray()[0];
                if (c=='t') { X="toFixed";id=Id_toFixed; }
                else if (c=='v') { X="valueOf";id=Id_valueOf; }
                goto L;
            case 8: c=s.ToCharArray()[3];
                if (c=='o') { X="toSource";id=Id_toSource; }
                else if (c=='t') { X="toString";id=Id_toString; }
                goto L;
            case 11: c=s.ToCharArray()[0];
                if (c=='c') { X="constructor";id=Id_constructor; }
                else if (c=='t') { X="toPrecision";id=Id_toPrecision; }
                goto L;
            case 13: X="toExponential";id=Id_toExponential; goto L;
            case 14: X="toLocaleString";id=Id_toLocaleString; goto L;
            }
        L:;
            if (X!=null && X!=s && !(X==s)) id = 0;
            goto L0;
        
        L0:;

        return id;
    }

        private const int
            Id_constructor = 1,
            Id_toString = 2,
            Id_toLocaleString = 3,
            Id_toSource = 4,
            Id_valueOf = 5,
            Id_toFixed = 6,
            Id_toExponential = 7,
            Id_toPrecision = 8,
            MAX_PROTOTYPE_ID = 8;

        // #/string_id_map#

        private double doubleValue;
    }
}
